using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ThridGroup.ERP.RBAC;
using ThridGroup.ERP.DTO;
using Volo.Abp.AspNetCore.Mvc.UI.RazorPages;
using Microsoft.AspNetCore.Authorization;
using System.Linq;

namespace ThridGroup.ERP.Web.Pages
{
    [Authorize]
    public class UserViewModel : AbpPageModel
    {
        private readonly IUserServices _userServices;
        private readonly IUserRoleServices _userRoleServices;
        private readonly IRoleServices _roleServices;

        public UserViewModel(
            IUserServices userServices,
            IUserRoleServices userRoleServices,
            IRoleServices roleServices)
        {
            _userServices = userServices;
            _userRoleServices = userRoleServices;
            _roleServices = roleServices;
        }

        public virtual async Task OnGetAsync()
        {
            await Task.CompletedTask;
        }

        public async Task<JsonResult> OnGetQueryUserAsync(int pageIndex = 1, int pageSize = 10)
        {
            var users = await _userServices.QueryUser();
            var total = users.Count;
            var pagedUsers = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return new JsonResult(new { 
                items = pagedUsers,
                totalCount = total
            });
        }

        public async Task<JsonResult> OnGetQueryRoleAsync()
        {
            var roles = await _roleServices.QueryRole();
            return new JsonResult(new { items = roles });
        }

        public async Task<JsonResult> OnGetFullUserRoleAsync(int id)
        {
            var userRole = await _userRoleServices.FullUserRole(id);
            return new JsonResult(userRole);
        }

        public async Task<JsonResult> OnPostAddUserRoleAsync([FromBody] UserRoleDto userRoleDto)
        {
            try
            {
                var result = await _userRoleServices.AddUserRole(userRoleDto);
                return new JsonResult(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, error = ex.Message });
            }
        }

        public async Task<JsonResult> OnDeleteUserAsync(int id)
        {
            try
            {
                var result = await _userServices.DeleteUser(id);
                return new JsonResult(new { success = result });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, error = ex.Message });
            }
        }

        [BindProperty]
        public UserDTO UserData { get; set; } = new UserDTO();
    }
} 